<template>
    <div class="map-box">
         <div id="map" class="myMap">
        </div>
        <!-- <el-button type="primary" class="upload" @click="toImg" icon="el-icon-crop">截图上传</el-button> -->
    </div> 
</template>

<script>
import FeatureStyle from '@/assets/dist/FeatureStyle'
import { saveAs } from 'file-saver'
export default {
    name: 'smap',
    props: {
        //图片列表
        pointdata: {
            type: Object
        },
        //截图触发
        clickMappicture:0
            },
    data() {
        return {
            // 底图 图层变量
            baseMapLayer :{
                tileLayer: new ol.layer.Tile({
                source: new ol.source.OSM({
                url: "http://t{1-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=4b82bec6c2d654c948e324589673371f"
                    })
                }),
                labelLayer: new ol.layer.Tile({
                    zIndex: 1,
                    source: new ol.source.OSM({
                    url: "http://t{1-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=4b82bec6c2d654c948e324589673371f"
                    })
                })
            },
            //变量
            MyMap:undefined,
            selectSingleClick:{},
            wktLayers : {},
            vetorList : [],
            overlay :undefined,
        };
    },
    watch:{
        clickMappicture(val){
            if (val!=0) {
                this.toImg()
            }
        }
    },
    mounted() {
        this.createMap(this.setCent(this.pointdata.theGeom));
        this.drawWKT(this.pointdata)
    },
    methods: {
        //设置中心点
        setCent(geo){
            if(geo){
               let coordinate = geo.replace('POINT(',"").replace(")","").split(" ")
                return [parseFloat(coordinate[0]),parseFloat(coordinate[1])]     
            }
            else{
                return [113.94261734587297, 22.57669954443905]
            }
        },
        toImg() {
            let that = this;
                this.MyMap.once('postcompose', function (event) {
                    var canvas = event.context.canvas;
                    canvas.toBlob(function (blob) {
                        that.$emit('selectPicture', blob,"map");
                        // saveAs(blob, 'map2.png')
                    })
                })
                this.MyMap.renderSync()
            },
         //地图相关==================================================================
        createMap(cent) {
            let setCen = cent?cent:[113.94261734587297, 22.57669954443905]
            this.MyMap = new ol.Map({
                target: 'map',
                logo: false,
                layers: null,
                interactions: ol.interaction.defaults({
                    doubleClickZoom: false
                }),
                view: new ol.View({
                    projection: "EPSG:4326",
                    center: setCen,
                    zoom: 17,
                    minZoom: 6,  
                    maxZoom: 18.5
                }),
                controls: ol.control.defaults({
 
                        attributionOptions: ({
                
                        collapsible: false
                
                        })
                
                    })

            })
            let temp = null
            const mousePositionControl = new ol.control.MousePosition({
                coordinateFormat: function (coordinate) {
                temp = coordinate
                    return ol.coordinate.format(coordinate, '经度:{x}°E 纬度:{y}°N', 2)
                },
                projection: 'EPSG:4326',
                className: 'ol-mouse-position',
                target: document.getElementById('mouse-position'),
            })
            
            this.MyMap.addLayer(this.baseMapLayer.tileLayer) //矢量图
            this.MyMap.addLayer(this.baseMapLayer.labelLayer) //影像图
            // 监听地图单击
            // map.on('singleclick', evt => {
            // 	console.log(evt.coordinate)
            // })
            //弹出气泡
            var container = document.getElementById('popup');
            var content = document.getElementById('popup-content');

            this.overlay = new ol.Overlay({
                element: container,
                autoPan: true,
                autoPanAnimation: {
                    duration: 250,
                },
            });
            this.MyMap.addOverlay(this.overlay);
        },
        // 设置底图 地图切换
        setBaseMap (layer) {
            this.MyMap.removeLayer(this.baseMapLayer.tileLayer)
            this.MyMap.removeLayer(this.baseMapLayer.labelLayer)
            let source = null
            let type = layer.typeName
            let url = layer.url
            let labelSource = this.baseMapLayer.labelLayer.getSource()
            if (labelSource) {
               this.baseMapLayer.labelLayer.setSource(null)
            }
            if (type === 'tianditu' || type === 'xyz') {
                source = new ol.source.XYZ({
                // crossOrigin: 'anonymous',
                url: url.split('|')[0]
                })
                let labelSource = new ol.source.XYZ({
                // crossOrigin: 'anonymous',
                url: url.split('|')[1]
                })
                this.baseMapLayer.labelLayer.setZIndex(-1)
                this.baseMapLayer.labelLayer.setSource(labelSource)
            }
                this.baseMapLayer.tileLayer.setSource(source)
                this.baseMapLayer.tileLayer.setZIndex(-2)
                this.MyMap.addLayer(this.baseMapLayer.tileLayer)
                this.MyMap.addLayer(this.baseMapLayer.labelLayer)
                this.MyMap.index = -1
            },
        //绘制图形
        drawWKT(geomstring) {
                let wkt = geomstring.theGeom
                let format = new ol.format.WKT(wkt)
                let feature = format.readFeature(wkt)
                const geoType = this.getGeoType(wkt); //判断数据点线面
                // let mycolor = geomstring.showColor
                let vectorWKT = new ol.layer.Vector({
                        source: new ol.source.Vector({
                            features: [feature]
                        }),
                        opacity: 0.9,
                        style:FeatureStyle.getStyle(geoType,geomstring.abStatus)
                })
                this.MyMap.removeInteraction(this.selectSingleClick);//移除之前的图层
                this.vetorList.push(vectorWKT)
                // selectSingles[geomstring.ID+geomstring.name] = selectSingleClick;
                // this.MyMap.addInteraction(this.selectSingleClick);
                // this.MyMap.selectSingleClick =this.selectSingleClick;
                // this.selectSingleClick.on('select', this.poiClick); //图层点击
                // this.wktLayers[geomstring[objId]+geomstring[objName]] = vectorWKT
                this.MyMap.addLayer(vectorWKT);
            },
        //移除绘制图层
        removeWKT (geomstring,objId,objName) {
            let wkt = geomstring[objId]+geomstring[objName]
            if(this.wktLayers[wkt]!=undefined) {
                let index = this.vetorList.indexOf(this.wktLayers[wkt])
                index>-1&&this.vetorList.splice(index, 1);
                this.MyMap.removeLayer(this.wktLayers[wkt])
                this.overlay.setPosition(undefined);
                delete this.wktLayers[wkt]
                }
            },
        clearWKT () {
            this.vetorList=[]
            Object.keys(this.wktLayers).forEach(key => {
                this.MyMap.removeLayer(this.wktLayers[key])
                delete this.wktLayers[key]
                })
            },
        //数据类型判断
        getGeoType(geo){
                if(geo.indexOf("POLYGON")!=-1){
                    return "POLYGON"
                }
                else if(geo.indexOf("LINESTRING")!=-1){
                    return "LINESTRING"
                }
                else if(geo.indexOf("minLine")!=-1){
                    return "minLine"
                }
                else if(geo.indexOf("POINT")!=-1){
                    return "ICON"
                }
                else if(geo.indexOf("ICON")!=-1){
                    return "ICON"
                }
                else if(geo.indexOf("oldICON")!=-1){
                    return "oldICON"
                }
                else{
                    return ""
                }
            }
    },
};
</script>

<style scoped>
.map-box{
    position: relative;
    width: 100%;
    height: 100%;
}
.myMap{
    position: absolute;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
}
.upload{
    position: absolute;
    bottom: 0px;
    right: 40%;
}
</style>